//
//  DiscoverViewController.m
//  weibo
//
//  Created by dllo on 16/6/13.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DiscoverViewController.h"
#import "AppDelegate.h"
#import "UserModel.h"
#import "ChatViewController.h"

@interface DiscoverViewController ()<UITableViewDataSource, UITableViewDelegate, EMChatManagerDelegate,EMChatManagerChatDelegate>

@property (nonatomic, strong)UITableView *myTableView;
@property (nonatomic, strong)NSArray *array;
// 好友用户名;
@property (nonatomic, copy)NSString *userName;


// 临时使用
@property (nonatomic, retain) NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableDictionary *myUserDic;
@property (nonatomic, retain) NSMutableArray *myKeyArray;


@end

@implementation DiscoverViewController

- (void)dealloc {
    [_myTableView release];
    [_array release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.myUserDic = [NSMutableDictionary dictionary];
    [self createView];

    //获取环信好友数据




    [self createData];
    //转换为本地数据
    [self key:self.myArray];
    // 所有key排序后组成的数组
    self.myKeyArray = [NSMutableArray arrayWithArray:self.myUserDic.allKeys];
    [self.myKeyArray sortUsingSelector:@selector(compare:)];
   
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(BarAction:)];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self createData];
}

- (void)BarAction:(UIBarButtonItem *)bar {
    [self buddyRequest];
}

- (void)didFetchedBuddyList:(NSArray *)buddyList
                      error:(EMError *)error {
    NSLog(@"%@",buddyList);
}

- (void)createView {
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49) style:UITableViewStylePlain];
    [self.view addSubview:self.myTableView];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    [_myTableView release];
    [[[EaseMob sharedInstance] chatManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
}

#pragma mark 协议方法
//分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.myKeyArray.count;
}
// TableView的点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *key = [self.myKeyArray objectAtIndex:indexPath.section];
    NSArray *arrayTp = [self.myUserDic objectForKey:key];
    UserModel *model = [arrayTp objectAtIndex:indexPath.row];
    
    ChatViewController *ChatVC = [[ChatViewController alloc] init];
    ChatVC.chatter = model.userName;
    [self.navigationController pushViewController:ChatVC animated:YES];
    [ChatVC release];

}


//显示分区名
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *sectonName = [self.myKeyArray objectAtIndex:section];
    return sectonName;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key = [self.myKeyArray objectAtIndex:section];
    return [[self.myUserDic objectForKey:key] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //添加cell
    NSString *key = [self.myKeyArray objectAtIndex:indexPath.section];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    //赋值
    NSArray *arrayTp = [self.myUserDic objectForKey:key];
    UserModel *model = [arrayTp objectAtIndex:indexPath.row];
    NSLog(@"%@",model.userName);
    cell.textLabel.text  = model.userName;
    return cell;
    
}



- (void)didAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error {
    NSLog(@"dsfkjlsdf");
    if (!error) {
        NSLog(@"自动登录成功");
        NSLog(@"%@",loginInfo);
    } else {
        NSLog(@"%@",error);
    }
}



// 好友申请处理结果回调
- (void)didAcceptedByBuddy:(NSString *)username {

    NSLog(@"======================%@",username);


    NSLog(@"%@",username);
    // 重新获取好友列表刷新tableView
    [self createData];


    NSLog(@"%@",username);
    // 重新获取好友列表刷新tableView
    [self createData];

}

- (void)didRejectedByBuddy:(NSString *)username {
    NSLog(@"%@",username);
}
- (void)buddyRequest {
    NSLog(@"dsjkfkjlsdfkj");
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"好友申请" message:@"确定" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.tag = 12000;
        [textField addTarget:self action:@selector(textAction:) forControlEvents:UIControlEventEditingChanged];
       
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        EMError *error = nil;
        BOOL isSuccess = [[[EaseMob sharedInstance] chatManager] addBuddy:self.userName message:@"我想加你为好友" error:&error];
        NSLog(@"%@",self.userName);
        if (isSuccess && !error) {
            NSLog(@"添加好友成功");
        } else {
            NSLog(@"%d",isSuccess);
            NSLog(@"%@",error);
        }
        
    }]];
    [self presentViewController:alert animated:YES completion:^{
        
        
    }];
}

//获取环信好友列表
-(void)createData{
    self.myArray = [NSMutableArray array];
    NSArray *array = [[EaseMob sharedInstance].chatManager buddyList];
    for (EMBuddy *emb in array) {
        UserModel *model = [[UserModel alloc] init];
        model.userName = emb.username;
        [self.myArray addObject:model];
        [model release];
    }
    [self.myTableView reloadData];
}


//创建字典
-(void)key:(NSMutableArray *)array{
    for (UserModel *modelTemp in array) {
        NSString *key = [[modelTemp.userName substringToIndex:1] uppercaseString];
        if ([[self.myUserDic allKeys] containsObject:key]) {
            NSMutableArray *arrayTemp = [self.myUserDic objectForKey:key];
            [arrayTemp addObject:modelTemp];
        }else{
            NSMutableArray *array1 = [NSMutableArray array];
            [array1 addObject:modelTemp];
            [self.myUserDic setObject:array1 forKey:key];
        }
    }
}



//右侧显示数组
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.myKeyArray;
}



- (void)textAction:(UITextField *)text {
    self.userName = text.text;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
